package concurrency;

public class ThisConcurrencyDemo implements Runnable{

    public static int n = 0;

    @Override
    public void run() {
        for(int i = 0; i < 10000000; i++){
            synchronized (this){
                n++;
            }
        }
    }

    /**
     * this关键字在synchronized中锁住的是当前对象。
     * 如果传入Thread实例的参数（实现Runnable接口对象）不是同一个的话，
     * 使用this当做锁是没用的
     * @param args
     */
    public static void main(String[] args) {
        ThisConcurrencyDemo demo = new ThisConcurrencyDemo();
        Thread thread1 = new Thread(demo);
        Thread thread2 = new Thread(demo);

        thread1.start();
        thread2.start();
        try {
            thread1.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(ThisConcurrencyDemo.n);
    }
}
